<template>
  <basic-container>
    <div class="header">
      <TitleComponent mainTitle="Vip配置" subTitle="列表"/>
      <el-button text type="primary" @click="router.push('/index')">主页</el-button>
    </div>
    <div class="crud_content">
      <avue-crud ref="crud" v-model="crudData.form" :before-close="beforeClose" :before-open="beforeOpen"
                 :data="crudData.data" :option="option" :page.sync="crudData.page" :table-loading="crudData.loading"
                 @refresh-change="refreshChange" @row-update="rowUpdate" @row-save="rowSave"
                 @selection-change="selectionChange"
                 @search-change="searchChange" @search-reset="searchReset" @current-change="currentChange"
                 @size-change="sizeChange" @on-load="onLoad">
        <template #menu-left="{ row }">
          <el-button class="btn" type="danger" @click="delsHandler">
            批量删除
          </el-button>
        </template>
        <template #menu="{ row }">
          <el-dropdown @command="(command) => handleCommand(command, row)">
            <el-icon size="20" style="rotate: 90deg;cursor: pointer">
              <More/>
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="edit">快捷编辑</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template #isUpgrade="{ row }">
          <el-switch v-model="row.isUpgrade" :active-value="1" :inactive-value="0"
                     style="--el-switch-on-color: #4E9876; " @click="(res: any) => changeName9(res, row)"/>
        </template>
        <template #isDisplay="{ row }">
          <el-switch v-model="row.isDisplay" :active-value="1" :inactive-value="0"
                     style="--el-switch-on-color: #4E9876; " @click="(res: any) => changeName9(res, row)"/>
        </template>
        <template #oreder="{ row }">
          <div class="order">
            <el-popover :visible="row.visible" :width="200" placement="right" trigger="click">
              <template #reference>
                <a href="javascript:void(0);" style="color: #4e9876; border-bottom: dashed 1px #4e9876;"
                   @click="row.visible = true"> {{
                    row.oreder
                  }}</a>
              </template>
              <div class="hover_box">
                <el-input v-model="row.oreder" placeholder=""></el-input>
                <div style="margin-top: 10px; display: flex;justify-content: flex-end;">
                  <el-button class="btn" type="" @click="row.visible = false">取消</el-button>
                  <el-button color="#4E9876" @click="orderSubmit(row)">提交</el-button>
                </div>
              </div>
            </el-popover>
          </div>
        </template>
        <template #openPrice-form="">
          <el-input v-model="crudData.form.openPrice" class="input-with-select" placeholder="请输入开通价格"
                    style="width: 100%">
            <template #prepend>
              $
            </template>
          </el-input>
        </template>
        <template #revenuePerOrder-form="">
          <el-input v-model="crudData.form.revenuePerOrder" class="input-with-select" placeholder="请输入每单收益"
                    style="width: 100%">
            <template #prepend>
              $
            </template>
          </el-input>
        </template>
        <template #serviceCharge-form="">
          <el-input v-model="crudData.form.serviceCharge" class="input-with-select" placeholder="请输入每单收益"
                    style="width: 100%">
            <template #prepend>
              %
            </template>
          </el-input>
        </template>
        <template #vipFirstLevelDistributionRate-form>
          <el-input v-model="crudData.form.vipFirstLevelDistributionRate"
                    class="input-with-select"
                    placeholder="请输入开通Vip一级分销比例">
            <template #prepend>
              %
            </template>
          </el-input>
        </template>
        <template #vipSecondLevelDistributionRate-form>
          <el-input v-model="crudData.form.vipSecondLevelDistributionRate"
                    class="input-with-select"
                    placeholder="请输入开通Vip二级分销比例">
            <template #prepend>
              %
            </template>
          </el-input>
        </template>
        <template #vipThirdLevelDistributionRate-form>
          <el-input v-model="crudData.form.vipThirdLevelDistributionRate"
                    class="input-with-select"
                    placeholder="请输入开通Vip三级分销比例">
            <template #prepend>
              %
            </template>
          </el-input>
        </template>
        <template #orderFirstLevelDistributionRate-form>
          <el-input v-model="crudData.form.orderFirstLevelDistributionRate"
                    class="input-with-select"
                    placeholder="请输入刷单一级分销比例">
            <template #prepend>
              %
            </template>
          </el-input>
        </template>
        <template #orderSecondLevelDistributionRate-form>
          <el-input v-model="crudData.form.orderSecondLevelDistributionRate"
                    class="input-with-select"
                    placeholder="请输入刷单二级分销比例">
            <template #prepend>
              %
            </template>
          </el-input>
        </template>
        <template #orderThirdLevelDistributionRate-form>
          <el-input v-model="crudData.form.orderThirdLevelDistributionRate"
                    class="input-with-select"
                    placeholder="请输入刷单三级分销比例">
            <template #prepend>
              %
            </template>
          </el-input>
        </template>
      </avue-crud>
    </div>
    <el-dialog v-model="crudData.confirmDeleteVisible" center class="custom-dialog" destroy-on-close title=""
               width="440">
      <div class="swal2-header">
        <div class="swal2-icon swal2-question swal2-animate-question-icon"></div>
        <div class="swal2_fs">确认删除？</div>
      </div>
      <div class="swal2_he">ID - {{ crudData.agentNumbers }}</div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="btn btn-primary" color="#488C6D" @click="handleDeleteConfirm">
            确认
          </el-button>
          <el-button class="btn" type="" @click="handleDeleteCancel">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </basic-container>
</template>
<script lang="ts" name="taskDetail" setup>
import {vipPage, vipRemove, vipSave, vipUpdate} from '@/api/user'
import {computed, reactive, ref} from 'vue';
import useUserStore from "@/store/modules/user";
import {ElMessage} from "element-plus";
import TitleComponent from '@/components/title/index.vue';
import BasicContainer from "@/components/basic-container/main.vue";
import {useRouter} from "vue-router";

const userStore = useUserStore();
const ids = computed(() => (crudData.selectionList.map(item => item.ID)))
const router = useRouter();
const crud: any = ref('')
const validatePass = (rule, value, callback) => {
  const regex = /^VIP\d{1,2}$/;
  if (!regex.test(value)) {
    callback(new Error('字符串必须以 "VIP" 开头并且紧跟着一或两位数字'));
  } else {
    callback();
  }
};
let option: any = reactive({
  saveBtn: true,
  updateBtn: true,
  cancelBtn: true,
  emptyBtn: false,
  submitBtn: false,
  height: 'auto',
  calcHeight: 80,
  searchShow: true,
  searchMenuSpan: 6,
  tip: true,
  border: true,
  index: false,
  viewBtn: false,
  editBtn: false,
  delBtn: false,
  addBtn: true,
  dialogWidth: '70%',
  menuWidth: '60',
  menuFixed: 'right',
  labelWidth: 170,
  menu: true,
  selection: true,
  searchLabelWidth: 120,
  indexLabel: '序号',
  refreshBtn: true, // 刷新按钮
  columnBtn: true,
  searchShowBtn: false,
  dialogMenuPosition: 'center',
  indexWidth: 60,
  column: [
    {
      label: "ID",
      prop: "id",
      disabled: true,
      hide: true,
      addDisplay: false,
      span: 24,
    },
    {
      label: "名称",
      prop: "name",
      span: 24,
      placeholder: '输入请以VIP开头加数字',
      prefixIcon: 'el-icon-edit',
      rules: [{validator: validatePass, trigger: 'blur'}]
    },
    // {
    //   label: "等级",
    //   prop: "level",
    //   display: false,
    //   span: 24,
    //   type: 'number',
    //   precision: 0,
    //   min: 0,
    //   controlsPosition: 'top',
    // },
    {
      label: '图标',
      prop: 'icon',
      type: 'upload',
      dragFile: true,
      dataType: 'string',
      listType: 'picture-img',
      accept: 'image/png, image/jpeg',
      limit: 1,
      span: 24,
      propsHttp: {
        name: 'originalFilename',
        url: 'url',
      },
      headers: {
        Authorization: `Bearer ${userStore.token}`
      },
      tip: '只能上传jpg/png用户头像',
      action: '/prod-api/common/upload'
    },
    {
      label: '背景图标',
      prop: 'backdropIcon',
      type: 'upload',
      dragFile: true,
      dataType: 'string',
      listType: 'picture-img',
      accept: 'image/png, image/jpeg',
      limit: 1,
      span: 24,
      propsHttp: {
        name: 'originalFilename',
        url: 'url',
      },
      headers: {
        Authorization: `Bearer ${userStore.token}`
      },
      tip: '只能上传jpg/png用户头像',
      action: '/prod-api/common/upload'
    },
    {
      label: "开通价格",
      prop: "openPrice",
      span: 24,
    },
    {
      label: "每日任务数",
      prop: "dailyTaskNum",
      type: 'number',
      precision: 0,
      width: '100',
      min: 0,
      controlsPosition: 'top',
      span: 13,
    },
    {
      label: "每单收益",
      prop: "revenuePerOrder",
      span: 24,
      prefixIcon: 'el-icon-plus',
    },
    {
      label: "每月可提现次数",
      prop: "monthWithdrawalNum",
      type: 'number',
      min: 0,
      precision: 0,
      controlsPosition: 'top', // 按钮位置-左右
      span: 13,
      width: '120',
      row: true,// 栅格后面的内容是否从新的一行开始展示
      rules: [
        {
          message: '请输入每月可提现次数',
          trigger: ['change', 'blur'],
          required: true,
        },
      ]
    },
    {
      label: "最小提现金额",
      prop: "minWithdrawMoney",
      type: 'number',
      min: 0,
      hide: true,
      precision: 2,
      controlsPosition: 'top', // 按钮位置-左右
      span: 13,
      width: '120',
      row: true,// 栅格后面的内容是否从新的一行开始展示
      rules: [
        {
          required: true,
          message: '请输入最小提现金额',
          trigger: ['change', 'blur'],
        },
        {
          validator: (rule: any, value: any, callback: any) => {
            if (value > crudData.form.maxWithdrawMoney) {
              callback(new Error('最大提现金额不能小于最小提现金额'));
            } else {
              callback();
            }
          },
          trigger: ['change', 'blur'],
        },
      ]
    },
    {
      label: "最大提现金额",
      prop: "maxWithdrawMoney",
      type: 'number',
      hide: true,
      min: 0,
      precision: 2,
      controlsPosition: 'top', // 按钮位置-左右
      span: 13,
      width: '120',
      row: true,// 栅格后面的内容是否从新的一行开始展示
      rules: [
        {
          required: true,
          message: '请输入最大提现金额',
          trigger: ['change', 'blur'],
        },
        {
          validator: (rule: any, value: any, callback: any) => {
            if (value < crudData.form.minWithdrawMoney) {
              callback(new Error('最大提现金额不能小于最小提现金额'));
            } else {
              callback();
            }
          },
          trigger: ['change', 'blur'],
        },
      ],
    },

    {
      label: "手续费率",
      prop: "serviceCharge",
      prefixIcon: 'el-icon-plus',
      span: 13,
      type: 'number',
      min: 0,
      precision: 0,
      rules: [
        {
          pattern: /^(100(\.0{1,})?|[1-9]?\d(\.\d{1,})?)$/,
          message: '请输入0-100的数字',
          trigger: 'change',
        }
      ],
      formatter: val => {
        return val.serviceCharge + '%';
      },
      // blur: (val: any) => {
      //   if (val.value) {
      //     console.log('PPP>>', val.value)
      //     if (!val.value.includes('%')) {
      //       crudData.form.serviceCharge = val.value + '%'
      //     }
      //   }
      // },
      row: true,// 栅格后面的内容是否从新的一行开始展示
    },
    {
      label: "Vip有效期(天)",
      prop: "validityPeriod",
      type: 'number',
      min: 0,
      precision: 0,
      width: '120',
      controlsPosition: 'top',
      span: 13,
      row: true,// 栅格后面的内容是否从新的一行开始展示
    },
    {
      label: "补差价升级",
      prop: "isUpgrade",
      width: '100',
      dataType: 'number',
      type: 'switch',
      value: '0',
      dicData: [{
        label: '',
        value: '0'
      }, {
        label: '',
        value: '1'
      }],
      span: 24,
    },
    {
      label: '开通Vip一级分销比例',
      prop: 'vipFirstLevelDistributionRate',
      span: 24,
      hide: true,
      rules: [
        {
          required: true,
          message: '请输入开通Vip一级分销比例',
          trigger: ['change', 'blur'],
        },
      ]
    },
    {
      label: '开通Vip二级分销比例',
      prop: 'vipSecondLevelDistributionRate',
      span: 24,
      hide: true,
      rules: [
        {
          required: true,
          message: '请输入开通Vip二级分销比例',
          trigger: ['change', 'blur'],
        },
      ]
    },
    {
      label: '开通Vip三级分销比例',
      prop: 'vipThirdLevelDistributionRate',
      span: 24,
      hide: true,
      rules: [
        {
          required: true,
          message: '请输入开通Vip三级分销比例',
          trigger: ['change', 'blur'],
        },
      ]
    },
    {
      label: '刷单一级分销比例',
      prop: 'orderFirstLevelDistributionRate',
      span: 24,
      hide: true,
      rules: [
        {
          required: true,
          message: '请输入刷单一级分销比例',
          trigger: ['change', 'blur'],
        },
      ]
    },
    {
      label: '刷单二级分销比例',
      prop: 'orderSecondLevelDistributionRate',
      span: 24,
      hide: true,
      rules: [
        {
          required: true,
          message: '请输入刷单二级分销比例',
          trigger: ['change', 'blur'],
        },
      ]
    },
    {
      label: '刷单三级分销比例',
      prop: 'orderThirdLevelDistributionRate',
      span: 24,
      hide: true,
      rules: [
        {
          required: true,
          message: '请输入刷单三级分销比例',
          trigger: ['change', 'blur'],
        },
      ]
    },
    {
      label: "展示",
      prop: "isDisplay",
      dataType: 'number',
      type: 'switch',
      value: '0',
      dicData: [{
        label: '',
        value: '0'
      }, {
        label: '',
        value: '1'
      }],
      span: 24,
    },
    {
      label: "排序",
      prop: "oreder",
      type: 'number',
      min: 0,
      precision: 0,
      controlsPosition: 'top', // 按钮位置-左右
      span: 24,
    },
    {
      label: "创建时间",
      prop: "createTime",
      type: 'datetime',
      // format: 'YYYY年MM月DD日 HH时mm分ss秒',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      display: false,
    },
    {
      label: "更新时间",
      prop: "updateTime",
      type: 'datetime',
      // format: 'YYYY年MM月DD日 HH时mm分ss秒',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      display: false,
    },
  ]
})
let crudData: any = reactive({
  confirmDeleteVisible: false,
  form: {},
  oprnType: '',
  agentNumbers: '',
  query: {},
  selectionList: [],
  loading: true,
  value1: '1',
  page: {
    pageSize: 10,
    currentPage: 1,
    total: 1
  },
  filedArr: [],
  data: []
})
const selectionChange = (list) => {
  crudData.selectionList = list
}
const delsHandler = () => {
  if (crudData.selectionList.length < 1) {
    ElMessage.warning('请选择至少一条数据');
    return;
  }
  crudData.agentNumbers = crudData.selectionList.map(item => item.id).join(',')
  crudData.confirmDeleteVisible = true
}

function refreshChange() {
  onLoad(crudData.page, crudData.query);
}

const handleDeleteCancel = () => {
  crudData.confirmDeleteVisible = false;
};

const handleDeleteConfirm = () => {
  vipRemove(crudData.agentNumbers).then(res => {
    ElMessage.success('操作成功')
    onLoad(crudData.page)
  }).catch(err => {
  })
  crudData.confirmDeleteVisible = false
};
const handleCommand = (command, row) => {
  if (command === 'edit') {
    crudData.rowData = row
    crud.value.rowEdit(row)
  } else if (command === 'delete') {
    crudData.agentNumbers = row.id
    crudData.confirmDeleteVisible = true;
  }
};

const handleSubmit = () => {
  crud.value.validate((valid: any, done: () => void, msg: any) => {
    if (valid) {
      ElMessage.success('操作成功');
      setTimeout(() => {
        done()
      }, 2000)
    }
  })
}
const handleEmpty = () => {
  crud.value.resetForm();
}
// 序号按钮提交
const orderSubmit = (row: { visible: boolean; }) => {
  vipUpdate(row).then(async () => {
    onLoad(crudData.page);
    ElMessage.success('操作成功');
    row.visible = false
  }).catch((error: any) => {
  })
}

// 翻页
function currentChange(currentPage: any) {
  crudData.page.currentPage = currentPage;
}

// 每页条数
function sizeChange(pageSize: any) {
  crudData.page.pageSize = pageSize;
}

// 重置
function searchReset() {
  crudData.query = {};
  onLoad(crudData.page);
}

// 列表模糊搜索
function searchChange(params: {} | undefined, done: () => void) {
  crudData.query = params;
  crudData.page.currentPage = 1;
  onLoad(crudData.page, params);
  done();
}

const getTrailingNumbers = (str, name) => {
  // 使用正则表达式提取字符串末尾的数字
  const match = str.match(/(\d+)$/);
  // 如果匹配成功，返回匹配的数字部分，否则返回 null
  let res = match ? match[1] : 0;
  if (name) {
    return removeLeadingZero(res)
  } else {
    return res
  }
}

function removeLeadingZero(str) {
  return str.replace(/\b0(\d)\b/g, '$1');
}

const rowSave = async (row: any, done: any, loading: any) => {
  console.log('>>>MMM', row)
  delete row.id
  row.name = 'VIP' + getTrailingNumbers(row.name, true)
  row.level = getTrailingNumbers(row.name, false)
  await vipSave(row).then(async () => {
    onLoad(crudData.page);
    ElMessage.success('操作成功');
    done();
  }).catch((error: any) => {
    loading()
  })
}

const rowUpdate = async (row: any, index: Number, done: any, loading: any) => {
  row.name = 'VIP' + getTrailingNumbers(row.name, true)
  row.level = getTrailingNumbers(row.name, false)
  await vipUpdate(row).then(async () => {
    onLoad(crudData.page);
    ElMessage.success('操作成功');
    done();
  }).catch((error: any) => {
    loading()
  })
}

// 弹窗打开前
function beforeOpen(done: any, type: any) {
  // type :类型 add -添加 edit -编辑 view -查看
  crudData.oprnType = type
  if (type === 'add') {
    crudData.form.creatDate = new Date()
  } else {
  }
  done() //  关闭弹窗
}

// 弹窗关闭前
const beforeClose = (done: () => void, type: any) => {
  done() //  关闭弹窗
}
const changeName9 = (res: any, row: any) => {
  vipUpdate(row).then(async () => {
    onLoad(crudData.page);
    // ElMessage.success('更新成功')
  }).catch((error: any) => {
  })
}
const onLoad = (page: any, params = {}) => {
  crudData.loading = true;
  vipPage(page.currentPage, page.pageSize, Object.assign(params, crudData.query)).then((res: any) => {
    const Data = res.data;
    crudData.page.total = Data.total;
    Data.records.forEach((item: any) => {
      item.isUpgrade = parseInt(item.isUpgrade)
      item.isDisplay = parseInt(item.isDisplay)
    })
    crudData.data = Data.records;
    crudData.loading = false;
  })
}
</script>
<style lang="scss" scoped>
.header {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-right: 2%;
}

.crud_content {
  width: 100%;
}

::v-deep span.avue-crud__img {
  width: 50px;
  height: 30px;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

::v-deep .el-popper {

  .hover_box {

    .btn_box {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;

      .btn {
        margin-right: 10px;
      }
    }
  }
}

.btns_box {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .view_btn {
    margin-right: 20px;
  }
}

.custom-dialog {
  display: flex;
  align-items: center;
  justify-content: center;
}

.swal2-header {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.swal2-icon {
  position: relative;
  box-sizing: content-box;
  justify-content: center;
  width: 5em;
  height: 5em;
  margin: 1.25em auto 1.875em;
  zoom: normal;
  border: 0.25em solid transparent;
  border-radius: 50%;
  line-height: 5em;
  cursor: default;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.swal2-icon.swal2-question::before {
  content: "?";
}

.swal2-icon::before {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 92%;
  font-size: 3.75em;
}

.swal2-icon.swal2-question {
  border-color: #c9dae1;
  color: #87adbd;
}

.swal2_fs {
  margin: 0 0 0.4em;
  padding: 0;
  font-size: 25px;
  color: #595959;
  text-align: center;
  font-weight: 400 !important;
}

.swal2_he {
  text-align: center;
  color: #545454;
  font-size: 1.125em;
  font-weight: 300;
  line-height: normal;
  word-wrap: break-word;
}
</style>
